package com.misboot.document.utils;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.http.HTMLFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * XSS 过滤工具类
 * 采用 hutool HTMLFilter
 *
 * @Author 湖南佐佑时代科技有限公司
 * @Version 5.4.21
 * @Email service@zuoyo.com
 * @Date 2022-06-16 13:31:39
 */
public class XssUtils {

    static Logger logger = LoggerFactory.getLogger(XssUtils.class);

    private static final ThreadLocal<HTMLFilter> HTML_FILTER = ThreadLocal.withInitial(() -> {
        HTMLFilter htmlFilter = new HTMLFilter();
        // 避免 " 被转成 &quot; 字符
        ReflectUtil.setFieldValue(htmlFilter, "encodeQuotes", false);
        return htmlFilter;
    });

    /**
     * XSS过滤
     *
     * @param content 需要过滤的内容
     * @return 返回过滤后的内容
     */
    public static String filter(String content) {
        logger.info("XSS过滤前的内容：" + content);
        String str = HTML_FILTER.get().filter(content);
        logger.info("XSS过滤后的内容：" + str);
        return str;
    }

}